<template>
    <div class="course-page">
        <div class="content-wrapper">
            <div class="box">
                <span>首页</span>
                <span class="separator">/</span>
                <span>课程搜索</span>
            </div>

            <div class="filters-wrapper">
                <div class="filter-box">
                    <span class="filter-label">专题:</span>
                    <div class="filter-tags">
                        <span 
                            @click="setFilter('subjectId', '')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.subjectId === '' }"
                        >
                            全部专题
                        </span>
                        <span 
                            v-for="course in allCourses" 
                            :key="course.courseId"
                            @click="setFilter('subjectId', course.courseId)" 
                            :class="{ 'filter-tag': true, 'active': searchParams.subjectId === course.courseId }"
                        >
                            {{ course.courseTitle }}
                        </span>
                    </div>
                </div>

                <div class="filter-box">
                    <span class="filter-label">类型:</span>
                    <div class="filter-tags">
                        <span 
                        @click="setFilter('type', '')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.type === '' }"
                        >
                            全部类型
                        </span>
                        <span 
                            @click="setFilter('type', 'free')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.type === 'free' }"
                        >
                            免费课程
                        </span>
                        <span 
                            @click="setFilter('type', 'pay')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.type === 'pay' }"
                        >
                            付费课程
                        </span>
                        <span 
                            @click="setFilter('type', 'boutique')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.type === 'boutique' }"
                        >
                            精品课程
                        </span>
                        <span 
                            @click="setFilter('type', 'discount')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.type === 'discount' }"
                        >
                            限时折扣课程
                        </span>
                    </div>
                </div>

                <div class="filter-box">
                    <span class="filter-label">方式:</span>
                    <div class="filter-tags">
                        <span 
                            @click="setFilter('courseType', '')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.courseType === '' }"
                        >
                            全部方式
                        </span>
                        <span 
                            @click="setFilter('courseType', 'live')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.courseType === 'live' }"
                        >
                            直播课程
                        </span>
                        <span 
                            @click="setFilter('courseType', 'recorded')" 
                            :class="{ 'filter-tag': true, 'active': searchParams.courseType === 'recorded' }"
                        >
                            录播课程
                        </span>
                    </div>
                </div>
            </div>

            <div class="course-row">
                <router-link 
                    v-for="course in paginatedCourses" 
                    :key="course.courseId"
                    :to="{ name: 'AboutView', query: { id: course.courseId } }"
                    class="course-link"
                >
                    <div class="course-card">
                        <img 
                            :src="course.bannerFileUrlPc || course.coverFileUrl" 
                            :alt="course.courseTitle" 
                            class="course-img"
                        >
                        <div class="course-title">{{ course.courseTitle }}</div>
                        <div class="course-meta">
                            共{{ course.subSectionNum }}节课 | {{ course.learningNum }}人学习
                        </div>
                        <div class="course-price">
                            <span v-if="course.isFree == 1" class="price-free">免费</span>
                            <template v-else-if="course.isDiscount == 1">
                                <span class="price-discount">¥{{ course.discountPrice }}</span>
                                <del class="price-original">¥{{ course.coursePrice }}</del>
                            </template>
                            <span v-else class="price-normal">¥{{ course.coursePrice }}</span>
                        </div>
                    </div>
                </router-link>
            </div>

            <div v-if="paginatedCourses.length === 0" class="empty-tip">
                暂无符合条件的课程
            </div>

            <div class="pagination" v-if="paginatedCourses.length > 0">
                <span 
                    v-for="page in pageNumbers" 
                    :key="page"
                    @click="changePage(page)"
                    :class="{ 'page-btn': true, 'current': searchParams.pageNum === page }"
                >
                    {{ page }}
                </span>
                <span class="page-count">共 {{ totalPages }} 页</span>
            </div>
        </div>
    </div>
</template>

<script>
import { getList } from '@/api/request';

export default {
    name: 'MainSearch',
    props: {
        searchKeyword: {
            type: String,
            default: ''
        },
        subjectId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            searchParams: {
                subjectId: this.subjectId,
                type: '',
                courseType: '',
                pageNum: 1,
                pageSize: 5, 
                keyword: this.searchKeyword 
            },
            allCourses: []
        };
    },
    watch: {
        searchKeyword(newVal) {
            this.searchParams.keyword = newVal;
            this.loadCourses();
        },
        subjectId(newVal) {
            this.searchParams.subjectId = newVal;
            this.loadCourses();
        }
    },
    computed: {
        filteredCourses() {
            return this.allCourses.filter(course => {
                const { subjectId, type, courseType, keyword } = this.searchParams;
                if (keyword && !course.courseTitle.includes(keyword)) return false;
                if (subjectId && String(course.courseId) !== String(subjectId)) return false;
                
                if (type === 'free') {
                    return String(course.isFree) === '1';
                }
                if (type === 'pay') return String(course.isFree) === '0';
                if (type === 'discount') return String(course.isDiscount) === '1';
                if (type === 'boutique') {
                    if ('isBoutique' in course) {
                        return String(course.isBoutique) === '1';
                    }
                    return false;
                }
                if (courseType && course.courseType !== courseType) return false;
                return true;
            });
        },
        totalPages() {
            return Math.ceil(this.filteredCourses.length / this.searchParams.pageSize);
        },
        pageNumbers() {
            const result = [];
            for (let i = 1; i <= this.totalPages; i++) {
                result.push(i);
            }
            return result;
        },
        paginatedCourses() {
            const { pageNum, pageSize } = this.searchParams;
            const start = (pageNum - 1) * pageSize;
            return this.filteredCourses.slice(start, start + pageSize);
        }
    },
    methods: {
        setFilter(key, value) {
            this.searchParams[key] = value;
            this.searchParams.pageNum = 1;
            this.loadCourses();
        },
        changePage(page) {
            this.searchParams.pageNum = page;  
            this.loadCourses();
        },
        loadCourses() {
            Promise.all([
                getList('free', this.searchParams.keyword),
                getList('boutique', this.searchParams.keyword),
                getList('discount', this.searchParams.keyword)
            ])
            .then(([freeRes, boutiqueRes, discountRes]) => {
                
                const boutiqueCourses = (boutiqueRes.rows || []).map(course => ({
                    ...course,
                    isBoutique: 1
                }));
                let allCourses = [
                    ...(freeRes.rows || []),
                    ...boutiqueCourses,
                    ...(discountRes.rows || [])
                ];

                const courseIdSet = new Set();
                allCourses = allCourses.filter(course => {
                    if (courseIdSet.has(course.courseId)) {
                        return false;
                    }
                    courseIdSet.add(course.courseId);
                    return true;
                });

                this.allCourses = allCourses.map(course => {
                    const types = ['live', 'recorded'];
                    return {
                        ...course,
                        courseType: types[Math.floor(Math.random() * types.length)]
                    };
                });
            })
        },
    },
    mounted() {
        this.searchParams.keyword = this.searchKeyword; 
        this.loadCourses();
    }
};
</script>

<style scoped lang="scss">
.content-wrapper {
    width: calc(100% - 40px);
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px 0;
}
.box {
    margin: 10px 0 20px;
    color: #666;
    font-size: 14px;
    .separator {
        margin: 0 8px;
        color: #999;
    }
}
.filters-wrapper {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-bottom: 25px;

    .filter-box {
        background: #f5f5f5; 
        padding: 10px 15px;
        display: flex;

        .filter-label {
            display: inline-block;
            min-width: 70px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            float: left;
            line-height: 30px;
            color: rgba(0, 0, 0, .5);
            font-size: 17px;
            margin-left: -22px;
        }

        .filter-tags {
            display: inline-flex;
            flex-wrap: wrap;
            gap: 10px;

            .filter-tag {
                cursor: pointer;
                font-size: 14px;
                color: #000; 
                line-height: 30px;
                display: inline-block;
                min-width: 70px;
                height: 30px;
                text-align: center;
                margin: 0 6px;
                padding: 0 5px;

                &.active {
                    background: #00cf8c;
                    color: white;
                    border-color: #00cf8c;
                }
            }
        }
    }
}
.course-row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10px; 
}
.course-link {
    width: calc(20% - 20px); 
    padding: 0 10px 20px;
    text-decoration: none;
}
.course-card {
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-radius: 20px;
    background: #fff;
    overflow: hidden;

    .course-img {
        width: 100%;
        height: 120px; 
        object-fit: cover;
        display: block;
    }

    .course-title {
        padding: 12px 15px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
        line-height: 1.4;
        height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
    }
    .course-meta {
        padding: 0 15px 8px;
        color: #888;
        font-size: 12px;
    }
    .course-price {
        padding: 0 15px 15px;
        display: flex;
        align-items: center;

        .price-free { 
            color: #00cf8c;
            font-weight: 600;
            font-size: 14px;
        }
        .price-discount { 
            color: #ff4500;
            font-weight: 600;
            font-size: 14px;
        }
        .price-original { 
            color: #999;
            font-size: 10px;
            margin-left: 6px;
            text-decoration: line-through;
        }
        .price-normal { 
            color: #ff4500;
            font-weight: 600;
            font-size: 14px;
        }
    }
}
.pagination {
    text-align: center;
    margin: 30px 0;

    .page-btn {
        display: inline-block;
        width: 30px;
        height: 30px;
        line-height: 30px;
        margin: 0 4px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;

        &.current { 
            background: #52c41a;
            color: white;
        }
    }
    .page-count {
        color: #666;
        margin-left: 10px;
    }
}

.empty-tip {
    text-align: center;
    padding: 60px 0;
    color: #999;
    font-size: 16px;
}
</style>